package com.kedacom.ctsp.authz.oauth2.util;

import com.kedacom.ctsp.authz.oauth2.configuration.KeyConfiguration;
import com.kedacom.ctsp.authz.oauth2.core.ErrorType;
import com.kedacom.ctsp.authz.oauth2.core.OAuth2Exception;
import com.kedacom.ctsp.lang.StringUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * @remark:
 * @ClassName JWTHelper
 * @Author fenghaiju
 * @date 2018/7/3
 **/
@Configuration
public class JWTHelper {
    @Autowired
    private KeyConfiguration keyConfiguration;

    public String getInfoFromToken(String token) throws Exception {
        try {
            return JWTUtil.getSubject(token, keyConfiguration.getUserPubKey());
        } catch (ExpiredJwtException ex) {
            String errorMsg = StringUtil.format("auth.authz.jwt.expired");
            throw new OAuth2Exception(ErrorType.EXPIRED_JWT_TOKEN, errorMsg);
        } catch (SignatureException ex) {
            String errorMsg = StringUtil.format("auth.authz.jwt.signature.error");
            throw new OAuth2Exception(ErrorType.ILLEGAL_JWT_TOKEN, errorMsg);
        } catch (IllegalArgumentException ex) {
            String errorMsg = StringUtil.format("auth.authz.jwt.isempty");
            throw new OAuth2Exception(ErrorType.ISEMPTY_JWT_TOKEN, errorMsg);
        }
    }
}
